﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using GCELibrary.Current;

using System.Linq.Dynamic;
using System.Linq.Expressions;
using ZF.BLL.Linq;
using ZF.BLL;
using ZF.Model;

namespace ZF.WS.shop
{
    public partial class buy : ZF.BLL.Page.GMPage
    {
        [PageArgument(Key = "id", CanNull = false)]
        public int MercId { get; set; }

        private Model.SP_Merchandise _Merc = null;
        public Model.SP_Merchandise Merc { get { return _Merc; } set { _Merc = this.header1.Merc = value; } }
        private Model.SP_Freight _Freight = null;
        public Model.SP_Freight Freight { get { return _Freight; } set { _Freight = this.header1.Freight = value; } }
        public int CIntegral { get; set; }
        public US_Member CMember { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetNoStore();
            Response.CacheControl = "no-cache";
            Response.AddHeader("Pragma", "No-Cache");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);


            object o;
            using (var dc = SiteInfo.CreateDBDataContext())
            {

                var merc = dc.SP_Merchandise.FirstOrDefault(p => p.MerchandiseId == MercId && !p.IsDel);
                if (merc == null)
                {
                    throw WarnFactory.CreateWarn("未找到该商品信息，可能该商品已经被删除", WarnIcon.Error, WarnLink.GoDefault);
                }

                merc.Hits++;
                dc.SubmitChanges();
                Merc = merc;
                Freight = merc.SP_Freight;
                var member = dc.US_Member.FirstOrDefault(p => p.MemberId == CurrentUser.MemberId);
                if (member == null)
                {
                    AlertTimeOut();
                }
                CMember = member;
                CIntegral = member.Integral;
            }

            if (!IsPostBack)
            {
                InitControls();
            }
        }

        protected void InitControls()
        {

            using (var dc = SiteInfo.CreateDBDataContext())
            {

                var info = dc.SP_Merchandise.FirstOrDefault(p => p.MerchandiseId == MercId && !p.IsDel);
                if (info == null)
                {
                    throw WarnFactory.CreateWarn("未找到该商品信息，可能该商品已经被删除", WarnIcon.Error, WarnLink.GoDefault);
                }
                this.Merc = info;
                this.rblFreight.DataSource = Merc.FreightSetList.Select(p =>
                     new
                     {
                         Key = p.Type,
                         Text = string.Format("{0}:{1}元", p.Name, p.Price),
                     });
                this.rblFreight.DataBind();
                //this.lvFreight.DataSource = Merc.FreightSetList;
                //this.lvFreight.DataBind();
                //if (!string.IsNullOrEmpty(this.Merc.Param))
                //{
                //    var paramList = Newtonsoft.Json.JsonConvert.DeserializeObject<Keyword<string>[]>(this.Merc.Param);
                //    this.lvParams.DataSource = paramList;
                //    this.lvParams.DataBind();
                //}

            }


            //if (Merc.IsToPay)
            //{
            //    this.rblWaybillType.Items.Insert(
            //        2, new ListItem("货到付款", "4")); 
            //}
        }
        protected void BuySubmit(object sender, EventArgs e)
        {

            if (!SiteInfo.ValidateCode(this.tbVCode.Text))
            {
                WarnFactory.CreateWarn(new PageWarnParameter()
                {
                    JscriptMode = true,
                    Link = WarnLink.GoBack,
                    Message = "验证码错误",
                }).Alert();
                return;
            }

            using (var ts = new System.Transactions.TransactionScope())
            {
                var quantity = this.tbQuantity.Text.Convert<int>();
                var integral = 0;

                if (this.tbPriceType.Text == "2")
                {

                    integral = this.Merc.Integral * quantity;
                    var success = SiteInfo.IntegralLog(CurrentUser.MemberId, "购买商品抵价", integral);
                    if (!success)
                    {
                        WarnFactory.CreateWarn(new PageWarnParameter()
                        {
                            JscriptMode = true,
                            Link = WarnLink.GoBack,
                            Message = "你的积分不足,请进行充值.",
                        }).Alert();
                        return;
                    }
                }
                using (var dc = SiteInfo.CreateDBDataContext())
                {
                    var freightPrice = this.Merc.FreightSetList.FirstOrDefault(a => a.Type == this.rblFreight.SelectedValue.Convert<int>()).Price;
                    if (Freight != null && this.tbArea1.Text != "")
                    {
                        var ftList = Freight.Json.JsonConvert<List<Keyword<string>>>();
                        var areaSet = ftList.FirstOrDefault(p => p.Key == this.tbArea1.Text);
                        if (areaSet != null)
                            freightPrice = areaSet.Text.Convert<int>();
                    }


                    var dcPrice = this.Merc.MPrice * quantity;
                    var op = this.Merc.MPrice;
                    if (this.tbPriceType.Text == "1")
                    {
                        dcPrice = this.Merc.MPrice * quantity;
                        op = this.Merc.MPrice;
                    }
                    else if (this.tbPriceType.Text == "2")
                    {
                        dcPrice = this.Merc.CPrice * quantity;
                        op = this.Merc.CPrice;
                    }
                    else
                        throw new Exception();
                    var lastPrice = dcPrice + freightPrice;



                    var order = new Model.SP_Order()
                    {
                        MemberId = this.CurrentUser.MemberId,
                        Address = this.tbArea.Text + this.tbAddress.Text,
                        AddTime = DateTime.Now,
                        OPrice = op,
                        Quantity = quantity,
                        DCPrice = dcPrice,
                        Discount = Merc.Discount,
                        LastPrice = lastPrice,
                        FreightType = this.rblFreight.SelectedValue.Convert<int>(),
                        PayType = this.rblPayType.SelectedValue.Convert<int>(),
                        FreightPrice = freightPrice,
                        Integral = integral,
                        Tel = this.tbPhone.Text,
                        Phone = this.tbPhone.Text,
                        Consignee = this.tbConsignee.Text,
                        MerchandiseId = Merc.MerchandiseId,
                        PubInfo = this.tbPubInfo.Text,
                        Unit = Merc.Unit,
                        WaybillNo = null,
                        WaybillCompany = null,
                        Zipcode = this.tbZipcode.Text,
                        Remark = null,
                        OrderNo = Guid.NewGuid().ToString(),
                        SerialNumber = null,
                        RecInfo = null,
                        IsDel = false,
                        Status = (int)OrderStatus.下单10,
                        IsPayed = false,
                        PayStatus = PayStatus.NEW_PAY.ToString(),
                        PSLastTime = DateTime.Now,
                        IsSend = false,

                    };

                    try
                    {
                        dc.SP_Order.InsertOnSubmit(order);
                        dc.SubmitChanges();
                        order.OrderNo = (10000 + order.OrderId).ToString();
                        dc.SubmitChanges();
                        ts.Complete();
                    }
                    catch (Exception ex)
                    {
                        throw WarnFactory.CreateWarn(ex);
                    }

                    if (order.PayType == (int)PayType.ZFB)
                    {
                        Response.Redirect(string.Format("/shop/pay.aspx?mid={1}&oId={0}", order.OrderId, order.MerchandiseId));
                    }
                    else if (order.PayType == (int)PayType.ToPay || order.PayType == (int)PayType.Bank)
                    {
                        var msg = "";
                        if (order.PayType == (int)PayType.ToPay)
                        {
                            msg = "订单创建成功，由于您选择货到付款的支付方式，我们将在短时间内联系您核实相关资料，敬请留意";
                        }
                        else if (order.PayType == (int)PayType.Bank)
                        {
                            msg = "订单创建成功，由于您选择银行转帐的支付方式，请您在银行转帐后与我们联系核对转帐金额，并发货.";
                        }

                        WarnFactory.CreateWarn(new PageWarnParameter()
                        {
                            JscriptMode = true,
                            Link = WarnLink.GoPage,
                            DoPage = string.Format("/shop/info.aspx?Id={0}", order.MerchandiseId),
                            Message = msg,
                        }).Alert();
                        return;
                    }
                    else
                    {
                        throw new Exception("未知支付方式");
                    }
                }

            }
        }
        /// <summary>
        /// 显示登录超时或未登录信息
        /// </summary>
        protected override void AlertTimeOut()
        {


            var from = Server.UrlEncode(Request.Url.ToString());
            this.WarnFactory.CreateWarn(new PageWarnParameter()
            {

                DoPage = string.Format("{0}?from={1}", LoginPage, from),
                Icon = WarnIcon.Error,
                JscriptMode = true,
                AlertPage = "",
                Link = WarnLink.GoLogin,
                Message = "当前状态未登录,请使用会员帐号登录后进行购买.\\r\\n如果没有会员帐号,在登录页面上点击注册新用户."
            }).Alert();




            ////显示登录超时信息
            //this.WarnFactory.CreateWarn(WarnCode.LoginTimeOut).Alert();
        }


    }

}
